﻿CREATE PROCEDURE [maint].[InitialiseDevice]
@DbName [sysname], @DeviceName [sysname], @OutputDiagnostics BIT=0
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int;
	SET @RC = 0;

	DECLARE @DeviceDoP int;
	SET @DeviceDoP = maint.GetDeviceDoP(@DbName);

	IF(@OutputDiagnostics = 1)
		BEGIN
			PRINT OBJECT_NAME(@@PROCID);
			PRINT N'	@DbName = N''' + ISNULL(@DbName,N'NULL') + '''';
			PRINT N'	@DeviceName = N''' + ISNULL(@DeviceName,N'NULL') + '''';
			PRINT N'	@DeviceDoP = ' + CAST(@DeviceDoP AS nvarchar);
		END

	BEGIN TRY
		EXEC @RC = util.CheckDevice @DeviceName, @OutputDiagnostics;
		EXEC @RC = maint.RotateDevice @DbName, @OutputDiagnostics;
		GOTO EXIT_PROC;
	END TRY
	BEGIN CATCH
		GOTO ADD_NEW_DEVICE;		
	END CATCH
	
ADD_NEW_DEVICE:
	EXEC @RC = maint.AddDevice @DeviceName, @DeviceDoP, @OutputDiagnostics;
	
EXIT_PROC:
	IF (@RC = 0)
	AND(@OutputDiagnostics = 1)
		PRINT 'Backup device [' + @DeviceName + '] initialised';

	RETURN(@RC)
END